package com.rmv.ums.condition;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public abstract class RegExCondition extends AbstractCondition {

	private static final Logger logger = Logger.getLogger(RegExCondition.class);

	private Pattern pattern = null;

	public boolean check(HttpServletRequest request) {

		if (logger.isDebugEnabled())
			logger.debug("checking request with condition:" + this);

		if (pattern == null)
			pattern = Pattern.compile(getValue());

		boolean ok = false;
		String toCheck = getValueToCheck(request);
		if (StringUtils.isNotBlank(toCheck)) {
			Matcher m = pattern.matcher(toCheck);
			ok = m.find();
		}

		if (logger.isDebugEnabled()) {
			if (ok) {
				logger.debug("request fulfill condition:" + this);
			} else {
				logger.debug("request doesn't fulfill condition:" + this);
			}
		}

		return ok;
	}

	public abstract String getValueToCheck(HttpServletRequest request);

}
